package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.entity.vo.AttrRespVo;
import com.atguigu.gulimall.product.entity.vo.Attrvo;
import com.atguigu.gulimall.product.service.CategoryService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("attrService")
@Slf4j
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Resource
    private AttrGroupDao attrGroupDao;

    @Resource
    private CategoryDao categoryDao;

    @Resource
    private CategoryServiceImpl categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(Attrvo attrvo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrvo,attrEntity);
        baseMapper.insert(attrEntity);
        //保存属性分组信息
        if (attrEntity.getAttrType() == 1) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attrvo.getAttrGroupId());
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    /**
     * 获取销售属性
     * @param params
     * @param catelogId
     * @param attrType
     * @return
     */
    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {

        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type","base".equalsIgnoreCase(attrType) ?
                        ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        //根据catelogId查询信息
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id",catelogId);
        }

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            //attr_id attr_name
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();

        List<AttrRespVo> respVos = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);

            //设置分类和分组的名字
            if ("base".equalsIgnoreCase(attrType)) {
                AttrAttrgroupRelationEntity relationEntity =
                        attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrEntity.getAttrId()));
                if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }

            }

            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());

            }
            return attrRespVo;
        }).collect(Collectors.toList());

        pageUtils.setList(respVos);
        return pageUtils;

    }

    @Transactional
    @Override
    public PageUtils selectAttrPageById(Map<String, Object> params, Long catelogId) {
        Page<AttrEntity> attrEntityPage = new Page<AttrEntity>(Long.parseLong((String) params.get("page")), Long.parseLong((String) params.get("limit")));
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (catelogId!=0){
            wrapper.eq("catelog_id",catelogId);
                if (!StringUtils.isEmpty(key)) {
                    wrapper.and((obj)->{
                        obj.eq("attr_id",key).or().like("attr_name",key);
                    });
                    }
            IPage<AttrEntity> page = baseMapper.selectPage(attrEntityPage, wrapper);
            List<AttrRespVo> respVos = page.getRecords().stream().map((attrEntity -> {
                        AttrRespVo attrRespVo = new AttrRespVo();
                        BeanUtils.copyProperties(attrEntity, attrRespVo);
                        AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                        if (relationEntity != null) {
                            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                            attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                        }
                        CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
                        if (categoryEntity != null) {
                            attrRespVo.setCatelogName(categoryEntity.getName());
                        }
                        return attrRespVo;
                    })
            ).collect(Collectors.toList());

            PageUtils pageUtils = new PageUtils(page);
            pageUtils.setList(respVos);
            return pageUtils;
        }else{
            IPage<AttrEntity> page = baseMapper.selectPage(attrEntityPage, new QueryWrapper<>());
            return new PageUtils(page);
        }
    }

    @Override
    public AttrRespVo selectBaseById(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity attrEntity = baseMapper.selectById(attrId);
        BeanUtils.copyProperties(attrEntity,attrRespVo);
        AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            attrRespVo.setAttrGroupId(relationEntity.getAttrGroupId());

        ArrayList<Long> arrayList = new ArrayList<>();
        List<Long> parentPath = categoryService.findParentPath(attrEntity.getCatelogId(), arrayList);


        Collections.reverse(parentPath);
        attrRespVo.setCatelogPath(parentPath);
        return attrRespVo;
    }

    @Override
    public void updateDetil(Attrvo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        baseMapper.updateById(attrEntity);

        //级联更新
        AttrAttrgroupRelationEntity relation = new AttrAttrgroupRelationEntity();
        relation.setAttrId(attrEntity.getAttrId());
        relation.setAttrGroupId(attr.getAttrGroupId());
        if (attr.getAttrType() == 1) {
            //如果原本就没有数据就要调用新增的方法
            AttrAttrgroupRelationEntity selectOne = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrEntity.getAttrId()));
            if (selectOne == null) {
                attrAttrgroupRelationDao.insert(relation);
            }
            //更新方法
            attrAttrgroupRelationDao.update(relation, new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
        }

    }

    @Override
    public PageUtils selectAttrSalePageById(Map<String, Object> params, Long catelogId) {
        Page<AttrEntity> attrEntityPage = new Page<AttrEntity>(Long.parseLong((String) params.get("page")), Long.parseLong((String) params.get("limit")));
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (catelogId!=0){
            wrapper.eq("catelog_id",catelogId);
            if (!StringUtils.isEmpty(key)) {
                wrapper.and((obj)->{
                    obj.eq("attr_id",key).or().like("attr_name",key);
                });
            }
            IPage<AttrEntity> page = baseMapper.selectPage(attrEntityPage, wrapper);
            List<AttrRespVo> respVos = page.getRecords().stream().map((attrEntity -> {
                        AttrRespVo attrRespVo = new AttrRespVo();
                        BeanUtils.copyProperties(attrEntity, attrRespVo);
                        AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                        if (relationEntity != null) {
                            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                            attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                        }
                        CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
                        if (categoryEntity != null) {
                            attrRespVo.setCatelogName(categoryEntity.getName());
                        }
                        return attrRespVo;
                    })
            ).collect(Collectors.toList());

            PageUtils pageUtils = new PageUtils(page);
            pageUtils.setList(respVos);
            return pageUtils;
        }else{
            IPage<AttrEntity> page = baseMapper.selectPage(attrEntityPage, new QueryWrapper<>());
            return new PageUtils(page);
        }
    }

//    private List<Long> RecursionQuery(Long catelogId,ArrayList<Long> arrayList){
//        List<CategoryEntity> list = categoryDao.selectList(new QueryWrapper<CategoryEntity>());
//
//        arrayList.add(catelogId);
//        List<Long> collect = list.stream().map((categoryEntity) -> {
//            Long parentCid = categoryEntity.getParentCid();
//            if (parentCid != 0 || ) {
//                arrayList.add(parentCid);
//            }
//            return categoryEntity.getParentCid();
//        }).collect(Collectors.toList());
//        return collect;
//    }


}